package top.lingkang.finalvalidated.handle;

import top.lingkang.finalvalidated.constraints.HasIntValue;
import top.lingkang.finalvalidated.core.FinalValidatorFactory;
import top.lingkang.finalvalidated.error.ValidatedException;
import top.lingkang.finalvalidated.utils.FinalValidatorUtils;

/**
 * @author lingkang
 * created by 2025/11/9 23:23
 */
public class HasIntValueHandle extends ValidHandle {
    private final String errorStr;
    private final HasIntValue hasIntValue;

    public HasIntValueHandle(ValidVal validVal, HasIntValue hasIntValue) {
        super(validVal, hasIntValue);
        this.hasIntValue = hasIntValue;

        if (FinalValidatorUtils.isNotEmpty(hasIntValue.message())) {
            errorStr = hasIntValue.message();
        } else if (FinalValidatorUtils.isNotEmpty(validVal.getTag())) {
            errorStr = FinalValidatorFactory.message.getProperty("HasIntValue")
                    .replace("{attrName}", validVal.getTag());
        } else {
            errorStr = FinalValidatorFactory.message.getProperty("HasIntValue")
                    .replace("{attrName}", validVal.getName());
        }
    }

    @Override
    public void valid(Object target) {
        Object o = validVal.getValGet().get(target);
        if (o == null || notHasIntValue(o)) {
            throw new ValidatedException(errorStr, validVal);
        }
    }

    private boolean notHasIntValue(Object target) {
        try {
            int integer = Integer.parseInt(target.toString());
            for (int i : hasIntValue.value()) {
                if (integer == i) {
                    return false;
                }
            }
        } catch (Exception e) {
            return true;
        }
        return true;
    }

    @Override
    public Class<?>[] getGroups() {
        return hasIntValue.groups();
    }
}
